import time
import base64

from Crypto.Cipher import DES3
from Crypto.Util.Padding import pad, unpad


def des3Encrypt(plain_text: str, key: str, iv: str) -> str:
    des3 = DES3.new(key=key.encode(), mode=DES3.MODE_CBC, iv=iv.encode())
    encrypted_data = des3.encrypt(pad(plain_text.encode(), DES3.block_size))
    cipher_text = base64.b64encode(encrypted_data).decode()
    return cipher_text


def des3Decrypt(cipher_text: str, key: str, iv: str) -> str:
    des3 = DES3.new(key=key.encode(), mode=DES3.MODE_CBC, iv=iv.encode())
    decrypted_data = des3.decrypt(base64.b64decode(cipher_text))
    plain_text = unpad(decrypted_data, DES3.block_size).decode()
    return plain_text

from binascii import a2b_hex
from binascii import b2a_hex

from Crypto.Cipher import DES


def desEncrypt(plain_text: str, key: str) -> str:
    des = DES.new(key=a2b_hex(key), mode=DES.MODE_ECB)
    encrypted_data = des.encrypt(a2b_hex(plain_text))
    return b2a_hex(encrypted_data).decode()


def desDecrypt(cipher_text: str, key: str) -> str:
    des = DES.new(key=a2b_hex(key), mode=DES.MODE_ECB)
    decrypted_data = des.decrypt(a2b_hex(cipher_text))
    return b2a_hex(decrypted_data).decode()


import base64
import hashlib
from binascii import a2b_hex
from binascii import b2a_hex

from Crypto.Cipher import AES
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
from loguru import logger


def myhash(data, flag="md5"):
    if hasattr(hashlib, flag):
        my_hash = getattr(hashlib, flag)()
    else:
        logger.warning("未定义hash类型", flag)
        return
    my_hash.update(data.encode("utf8"))
    hash_data = my_hash.hexdigest()
    return hash_data


def pkcs7padding(text):
    bs = AES.block_size
    length = len(text)
    bytes_length = len(bytes(text, encoding='utf-8'))
    padding_size = length if bytes_length == length else bytes_length
    padding = bs - padding_size % bs
    padding_text = chr(padding) * padding
    return text + padding_text


def pkcs7unpadding(text):
    length = len(text)
    unpadding = ord(text[length - 1])
    return text[0:length - unpadding]


def aesEncrypt(content, key, iv="", encode="BASE64"):
    """
    AES 加密
    :param content: 待加密文本
    :param key: AES key
    :param iv: AES iv(CBC模式才需要)
    :param encode: HEX/BASE64
    :return:
    """
    mode = "CBC" if iv else "ECB"
    if mode == "ECB":
        key_bytes = bytes(key, encoding='utf-8')
        cipher = AES.new(key_bytes, AES.MODE_ECB)
        content_padding = pkcs7padding(content)
        encrypt_bytes = cipher.encrypt(bytes(content_padding, encoding='utf-8'))
    else:
        key_bytes = bytes(key, encoding='utf-8')
        iv_bytes = bytes(iv, encoding='utf-8')
        cipher = AES.new(key_bytes, AES.MODE_CBC, iv_bytes)
        content_padding = pkcs7padding(content)
        encrypt_bytes = cipher.encrypt(bytes(content_padding, encoding='utf-8'))
    if encode == "BASE64":
        result = str(base64.b64encode(encrypt_bytes), encoding='utf-8')
    else:
        result = str(b2a_hex(encrypt_bytes), encoding='utf-8')
    return result


def aesDecrypt(content, key, iv="", encode="BASE64"):
    """
    AES 解密
    :param content: 待解密文本
    :param key: AES key
    :param iv: AES iv(CBC模式才需要)
    :param encode: BASE64/HEX
    :return:
    """
    mode = "CBC" if iv else "ECB"
    if mode == "EBC":
        key_bytes = bytes(key, encoding='utf-8')
        cipher = AES.new(key_bytes, AES.MODE_ECB)
    else:
        key_bytes = bytes(key, encoding='utf-8')
        iv_bytes = bytes(iv, encoding='utf-8')
        cipher = AES.new(key_bytes, AES.MODE_CBC, iv_bytes)
    if encode == "BASE64":
        encrypt_bytes = base64.b64decode(content)
    else:
        encrypt_bytes = a2b_hex(content)
    decrypt_bytes = cipher.decrypt(encrypt_bytes)
    result = str(decrypt_bytes, encoding='utf-8')
    result = pkcs7unpadding(result)
    return result


def rsaEncryptByKey(content, key, encode="BASE64"):
    """

    :param content: 待加密文本
    :param key: PublicKey
    :param encode: BASE64/HEX
    :return:
    """
    key = "-----BEGIN PUBLIC KEY-----\n" + key + "\n-----END PUBLIC KEY-----"
    rsakey = RSA.importKey(key)
    cipher = PKCS1_v1_5.new(rsakey)
    if encode == "BASE64":
        cipher_text = base64.b64encode(cipher.encrypt(content.encode('utf-8')))
    else:
        cipher_text = b2a_hex(cipher.encrypt(content.encode('utf-8')))
    return cipher_text.decode('utf-8')


def rsaEncryptByModule(content, module, pubKey="10001", encode="HEX"):
    """

    :param content: 待加密文本
    :param module: HEX 编码的 module
    :param pubKey: 默认 10001
    :param encode: BASE64/HEX
    :return:
    """
    pubKey = int(pubKey, 16)
    modules = int(module, 16)
    pubobj = RSA.construct((modules, pubKey), False)
    public_key = pubobj.publickey().exportKey().decode()
    rsakey = RSA.importKey(public_key)
    cipher = PKCS1_v1_5.new(rsakey)
    if encode == "BASE64":
        cipher_text = base64.b64encode(cipher.encrypt(content.encode('utf-8')))
    else:
        cipher_text = b2a_hex(cipher.encrypt(content.encode('utf-8')))
    return cipher_text.decode('utf-8')

if __name__ == '__main__':
    import base64
    import json
    from Crypto.Cipher import AES


    # content = '{"loginName":"18735914949","password":"li123456","captcha":"10","isKeepLogin":0}'
    # key = 'zg35ws76swnxz679'
    # iv = 'z66qa18l0w9o521k'
    # print(aesEncrypt(content,key,iv=iv))

    # Gong2268792


    # content = 'OE44VbtMu0yPd3ZkA101WTlzyXQftAvzSOtQ3vYAoztFi1OJmY9+KVgeUWgpxeDf9QMSLOOgCtZy4cWGDyvdeZt3pHr/FIqEmQawhQlc3gc6SI7VgTm1khfoF/+ya3zOXahd4Vf8da+7FunswjweNR3D1hLkk1YMHcj+sPwZtmanKClgJec36BHpTGHLYcWFHQj7gekvzoYq9/5cRjnPJAMOznYpheGSmRwD/ZkpDg1zx92SF8Lo6eyhLw6nqj5FtRkt3ROFukvwrV4t8hBW2INUuMQfvQnRL8VvWbRuUz1d6Ha3+SZtruCtAYkaiLgSz2dH7uh5w+Is4Xrzz3f4vtS4/VuzI+sKpjEYAcHPwvwn2TRFjskcwTQ7H/u4cQIerlPSw5vIl1JTNIvR6MYrkPVXt0GAVLuBgz8+PXaX9UnWVa33xZSVIeOOSuT1HIwiHNx/ZSfklLojutpqGhnsmg9Ila5krATWLDaUQvZlRWlv2fZ+Tr2FlfkmrscQi3VRe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'
    iv = 'z66qa18l0w9o521k'
    print(aesDecrypt(content, key, iv=iv))










